﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace paddle_ocrlabel
{
    static class Program
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);

        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string resourceName = "paddle_ocrlabel." + new AssemblyName(args.Name).Name + ".dll";
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                byte[] assemblyData = new byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            bool createNew;
            using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form5());
                }
                else
                {
                    MessageBox.Show("您已经打开该程序啦~~");
                    Process current = Process.GetCurrentProcess();
                    Process[] processes = Process.GetProcessesByName(current.ProcessName);
                    //遍历与当前进程名称相同的进程列表 
                    foreach (Process process in processes)
                    {
                        //如果实例已经存在则忽略当前进程 
                        if (process.Id != current.Id)
                        {
                            //保证要打开的进程同已经存在的进程来自同一文件路径
                            if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                            {
                                ShowWindowAsync(process.MainWindowHandle, 1);  //调用api函数，正常显示窗口
                                SetForegroundWindow(process.MainWindowHandle); //将窗口放置最前端
                            }
                        }
                    }
                }
            }
        }
    }
}
